import {ContentPayload} from '../sdk/RequestHandleSDK';

export class PayloadUtil {
  /**
     * 获取 ContentPayload 中的数据
     * @param payload ContentPayload 对象
     * @returns Map<string, string> 将数据封装成 Map 对象返回
     */
  static getPayloadData(payload: ContentPayload): Map<string, string> {
    // 检查 payload 是否有效
    if (!payload || !payload.data) {
      return new Map<string, string>();
    }
    const map = new Map<string, string>();
    // 如果value是数组，则转换为json字符串
    for (const [key, value] of payload.data.entries()) {
      if (typeof value === 'string' || typeof value === 'number') {
        map.set(key, String(value));
      } else if (Array.isArray(value)) {
        map.set(key, JSON.stringify(value));
      } else {
        console.log(`Value type is unknown. type is ${typeof value}`);
      }
    }
    return map;
  }

  /**
     * 获取 ContentPayload 中的上下文数据
     * @param key ContextValueKeyEnum
     * @param payload
     * @param valueType
     */
  static getContextValue<T>(key: string, payload: ContentPayload): T {
    const dataMap = this.getPayloadData(payload);
    const value = dataMap.get(key);
    if (!value) {
      return '' as T;
    }
    return value as T;
  }
}
